package Tools;

import pyrachnid.model.ground_model.Cell;
import pyrachnid.model.ground_model.Fire;
import pyrachnid.model.scenar_model.Scenario;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * @author zygou
 *
 */
public class CellConverterXML implements Converter {
	
	private Scenario _scenar;
	
	public CellConverterXML(Scenario scenar){_scenar = scenar;}
	
	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class cellClass) {
		return cellClass.equals(Cell.class);
	}

	@Override
	public void marshal(Object cellObject, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		//cast map object
		Cell cell = (Cell)cellObject;
		
		writer.startNode("Cell");
		//write atributes
		writer.addAttribute("x", String.valueOf(cell.getPositionX()));
		writer.addAttribute("y", String.valueOf(cell.getPositionY()));
		writer.addAttribute("burned", String.valueOf(cell.getHasbeenBurn()));
		
		Fire fire = cell.getFire();
		if(fire != null){
			writer.startNode("fire");
			writer.addAttribute("intensity", String.valueOf(fire.getFireIntensity()));
			writer.endNode();
		}
		writer.endNode();

	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		
		Cell[][] cells = _scenar.getMap().getGround();
		
		int posX = Integer.valueOf(reader.getAttribute("x"));
		int posY = Integer.valueOf(reader.getAttribute("y"));
		boolean burned = Boolean.valueOf(reader.getAttribute("burned"));
		cells[posX][posY].setHasBeenBurn(burned);
		if(reader.hasMoreChildren()){
			reader.moveDown();
				cells[posX][posY].setFire(new Fire(Integer.valueOf(reader.getAttribute("intensity"))));
			reader.moveUp();
		}
		return null;
	}

}
